/*
 *  vTeacherMainForm.java
 *
 *  Copyright (C) 2011  Nikos Paraschou
 *
 *  This file is part of "vTeacher".
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package vteacher;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author nikos
 */
public class vTeacherMainForm extends javax.swing.JFrame {

    /** Creates new form vTeacherMainForm */
    public vTeacherMainForm() {
        try {
	    // Set System L&F
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (UnsupportedLookAndFeelException e) {
           // handle exception
        }
        catch (ClassNotFoundException e) {
           // handle exception
        }
        catch (InstantiationException e) {
           // handle exception
        }
        catch (IllegalAccessException e) {
           // handle exception
        }

        initComponents();

        setLocationRelativeTo(null);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fc = new javax.swing.JFileChooser();
        loadDictButton = new javax.swing.JButton();
        previousButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        aboutButton = new javax.swing.JButton();
        aboutLabel = new javax.swing.JLabel();
        dictNameLabel = new javax.swing.JLabel();
        wordCountLabel = new javax.swing.JLabel();
        translateButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        untranslatedTextArea = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        translatedTextArea = new javax.swing.JTextArea();
        currentWordNumberLabel = new javax.swing.JLabel();
        searchTextField = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        loadDictButton.setText("Load Dictionary");
        loadDictButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadDictButtonActionPerformed(evt);
            }
        });

        previousButton.setText("Previous");
        previousButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previousButtonActionPerformed(evt);
            }
        });

        nextButton.setText("Next");
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });

        exitButton.setText("Exit");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        aboutButton.setText("About");
        aboutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutButtonActionPerformed(evt);
            }
        });

        translateButton.setText("Translate!");
        translateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                translateButtonActionPerformed(evt);
            }
        });

        untranslatedTextArea.setBackground(java.awt.Color.lightGray);
        untranslatedTextArea.setColumns(20);
        untranslatedTextArea.setFont(new java.awt.Font("FreeSans", 1, 18));
        untranslatedTextArea.setLineWrap(true);
        untranslatedTextArea.setRows(5);
        untranslatedTextArea.setText("\n\n Load a dictionary and press Next to start.");
        jScrollPane1.setViewportView(untranslatedTextArea);

        translatedTextArea.setBackground(java.awt.Color.lightGray);
        translatedTextArea.setColumns(20);
        translatedTextArea.setFont(new java.awt.Font("FreeSans", 0, 18));
        translatedTextArea.setLineWrap(true);
        translatedTextArea.setRows(5);
        jScrollPane2.setViewportView(translatedTextArea);

        currentWordNumberLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        searchTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchTextFieldActionPerformed(evt);
            }
        });

        searchButton.setText("Search");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(currentWordNumberLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 786, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(loadDictButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dictNameLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(wordCountLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 786, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 786, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(previousButton)
                        .addGap(18, 18, 18)
                        .addComponent(translateButton, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(nextButton))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(aboutButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(aboutLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 654, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exitButton)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {nextButton, previousButton});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {aboutButton, exitButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loadDictButton)
                    .addComponent(dictNameLabel)
                    .addComponent(wordCountLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(currentWordNumberLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(previousButton)
                    .addComponent(nextButton)
                    .addComponent(translateButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(exitButton)
                    .addComponent(aboutButton)
                    .addComponent(aboutLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitButtonActionPerformed

    private void aboutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutButtonActionPerformed
        String name = "vTeacher version 0.1 | ";
        String developer = "Nikos Paraschou | ";
        String l = "License: ";
        String license = "GPLv3";
        String about = name + developer + l + license;
        aboutLabel.setText(about);
    }//GEN-LAST:event_aboutButtonActionPerformed

    private void loadDictButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadDictButtonActionPerformed
        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            // Get the selected file (dictionary).
            dictFile = fc.getSelectedFile();

            // Allow max 40 characters of the dictionary name to be visible.
            // To keep the GUI in good shape.
            String fname = dictFile.getName();
            if(fname.length() > 40)
                dictNameLabel.setText(fname.substring(0, 40));
            else
                dictNameLabel.setText(fname);

            // read and load the contents of the dictionary.

            // reset the variables in memory
            dictWords = new ArrayList<String>();
            wordCount = 0;
            wordIndex = -1;
            BufferedReader reader = null;

            try {
                reader = new BufferedReader(new FileReader(dictFile));
                String text = null;

                // repeat until all lines are read
                while ((text = reader.readLine()) != null)
                {
                    dictWords.add(text);
                    // Count the dictionary's words.
                    wordCount++;
                }
            }
            catch (FileNotFoundException e) {
                System.out.println(e.getMessage());
            }
            catch (IOException e) {
                System.out.println(e.getMessage());
            }
            finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                }
                catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }

            // shuffle the words
            java.util.Collections.shuffle(dictWords);

            // show file contents here
            for(int i = 0; i < dictWords.size(); i++) {
                System.out.println(dictWords.get(i));
            }

            wordCountLabel.setText(String.valueOf(wordCount) + " λέξεις");

        }
        else {
            System.out.println("Open command cancelled by user.");
        }

    }//GEN-LAST:event_loadDictButtonActionPerformed

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        if(dictFile == null)
            return;

        translateButton.setEnabled(true);

        // the index of the next word
        wordIndex++;

        // recycle if the upper end is reached
        if(wordIndex == wordCount)
            wordIndex = 0;

        // print the current word
        String currentWord = dictWords.get(wordIndex);
        try {
            untranslatedTextArea.setText(currentWord.substring(0, currentWord.indexOf(':')));
            translatedTextArea.setText("");
            translateButton.requestFocus();

            currentWordNumberLabel.setText((wordIndex + 1) + " / " + wordCount);
        }
        catch(Exception exc) {
            untranslatedTextArea.setText("Εεε χωριό. Τι λεξικό είναι αυτό; Δε διαβάζεται...");
            dictFile = null;
        }
    }//GEN-LAST:event_nextButtonActionPerformed

    private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousButtonActionPerformed
        if(dictFile == null)
            return;

        translateButton.setEnabled(true);

        // the index of the previous word
        wordIndex--;

        // recycle if the lower end is reached
        if(wordIndex < 0)
            wordIndex = wordCount - 1;
        
        // print the previous word
        String previousWord = dictWords.get(wordIndex);
        try {
            untranslatedTextArea.setText(previousWord.substring(0, previousWord.indexOf(':')));
            translatedTextArea.setText("");
            translateButton.requestFocus();

            currentWordNumberLabel.setText((wordIndex + 1) + " / " + wordCount);
        }
        catch(Exception exc) {
            untranslatedTextArea.setText("Εεε χωριό. Τι λεξικό είναι αυτό; Δε διαβάζεται...");
            dictFile = null;
        }
    }//GEN-LAST:event_previousButtonActionPerformed

    private void translateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_translateButtonActionPerformed
        if(dictFile == null || wordIndex == -1)
            return;

        String currentWord = dictWords.get(wordIndex);
        String translation = currentWord.substring(currentWord.indexOf(':'), currentWord.length());
        translatedTextArea.setText(translation);

        nextButton.requestFocus();
    }//GEN-LAST:event_translateButtonActionPerformed

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        if(searchTextField.getText() == null || dictWords == null)
            return;

        String searchStr = searchTextField.getText();

        for(int i = 0; i < dictWords.size(); i++) {
            if(dictWords.get(i).contains(searchStr)) {
                String dictWord = dictWords.get(i);

                untranslatedTextArea.setText(dictWord.substring(0, dictWord.indexOf(':')));
                String translation = dictWord.substring(dictWord.indexOf(':'), dictWord.length());
                translatedTextArea.setText(translation);

                translateButton.setEnabled(false);

                break;
            }
        }
    }//GEN-LAST:event_searchButtonActionPerformed

    private void searchTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchTextFieldActionPerformed
        searchButtonActionPerformed(evt);
    }//GEN-LAST:event_searchTextFieldActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new vTeacherMainForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aboutButton;
    private javax.swing.JLabel aboutLabel;
    private javax.swing.JLabel currentWordNumberLabel;
    private javax.swing.JLabel dictNameLabel;
    private javax.swing.JButton exitButton;
    private javax.swing.JFileChooser fc;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton loadDictButton;
    private javax.swing.JButton nextButton;
    private javax.swing.JButton previousButton;
    private javax.swing.JButton searchButton;
    private javax.swing.JTextField searchTextField;
    private javax.swing.JButton translateButton;
    private javax.swing.JTextArea translatedTextArea;
    private javax.swing.JTextArea untranslatedTextArea;
    private javax.swing.JLabel wordCountLabel;
    // End of variables declaration//GEN-END:variables

    private File dictFile = null;
    private ArrayList<String> dictWords = null;
    private int wordCount = 0;
    private int wordIndex = -1;
}
